package com.pengtu.web.contract;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.pengtu.Constants;
import com.pengtu.dao.Page;
import com.pengtu.dao.QueryFilter;
import com.pengtu.entity.app.Attachment;
import com.pengtu.entity.app.User;
import com.pengtu.entity.contract.Document;
import com.pengtu.entity.history.HistoryProject;
import com.pengtu.security.SpringSecurityUtils;
import com.pengtu.service.app.SystemManager;
import com.pengtu.service.contract.AccordingManager;
import com.pengtu.service.history.HistoryProjectManager;
import com.pengtu.service.quality.FprojectManager;
import com.pengtu.utils.DateUtils;
import com.pengtu.utils.web.ControlHelpUtil;
import com.pengtu.utils.web.Struts2Utils;
import com.pengtu.web.BaseActionSupport;

@Results({
		@Result(name = "itemList", location = "${ctx}/contract/itemlist.action?cid=${id}", type = "redirect"),
		@Result(name = "part0", location = "${ctx}/contract/document!login.action?id=${id}", type = "redirect"),
		@Result(name = Constants.OVER, location = "${ctx}/contract/document.action", type = "redirect"),
		@Result(name = BaseActionSupport.RELOAD, location = "${ctx}/contract/document/history.action?key=${id}&pngFileName=document.png", type = "redirect"),
		@Result(name = Constants.START, location = "${ctx}/contract/document!taketask.action?id=${id}&taskid=${taskid}&status=${status}", type = "redirect"),
		@Result(name = "part1", location = "${ctx}/contract/document!one.action?id=${id}&taskid=${taskid}", type = "redirect"),
		@Result(name = "part2", location = "${ctx}/contract/document!two.action?id=${id}&taskid=${taskid}", type = "redirect"),
		@Result(name = "part3", location = "${ctx}/contract/document!three.action?id=${id}&taskid=${taskid}", type = "redirect"),
		@Result(name = "", location = "", type = "redirect") })
public class DocumentAction extends BaseActionSupport<Document> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Document document;
	private AccordingManager accordingManager;
	private String id;
	private Page<Document> page = new Page<Document>(10);
	private String cid;
	private String projectId;
	private File upload;
	private String uploadFileName;
	private String uploadContentType;
	private SystemManager systemManager;
	private FprojectManager fProjectManager;
	private HistoryProjectManager historyProjectManager;
	private String taskid;
	private User user = SpringSecurityUtils.getCurrentUser();
	private String status;

	/**
	 * @param fProjectManager
	 *            the fProjectManager to set
	 */
	@Autowired
	public void setfProjectManager(FprojectManager fProjectManager) {
		this.fProjectManager = fProjectManager;
	}

	/**
	 * @param historyProjectManager
	 *            the historyProjectManager to set
	 */
	@Autowired
	public void setHistoryProjectManager(
			HistoryProjectManager historyProjectManager) {
		this.historyProjectManager = historyProjectManager;
	}

	/**
	 * uploadFileName
	 * 
	 * @return the uploadFileName
	 * @since 1.0.0
	 */

	public String getUploadFileName() {
		return uploadFileName;
	}

	/**
	 * @param uploadFileName
	 *            the uploadFileName to set
	 */
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	/**
	 * uploadContentType
	 * 
	 * @return the uploadContentType
	 * @since 1.0.0
	 */

	public String getUploadContentType() {
		return uploadContentType;
	}

	/**
	 * @param uploadContentType
	 *            the uploadContentType to set
	 */
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	/**
	 * upload
	 * 
	 * @return the upload
	 * @since 1.0.0
	 */

	public File getUpload() {
		return upload;
	}

	/**
	 * @param upload
	 *            the upload to set
	 */
	public void setUpload(File upload) {
		this.upload = upload;
	}

	@Autowired
	public void setSystemManager(SystemManager systemManager) {
		this.systemManager = systemManager;
	}

	/**
	 * status
	 * 
	 * @return the status
	 * @since 1.0.0
	 */

	public String getStatus() {
		return status;
	}

	/**
	 * @param status
	 *            the status to set
	 */
	public void setStatus(String status) {
		this.status = status;
	}

	/**
	 * projectId
	 * 
	 * @return the projectId
	 * @since 1.0.0
	 */

	public String getProjectId() {
		return projectId;
	}

	/**
	 * @param projectId
	 *            the projectId to set
	 */
	public void setProjectId(String projectId) {
		this.projectId = projectId;
	}

	public String getCid() {
		return cid;
	}

	public void setCid(String cid) {
		this.cid = cid;
	}

	public Document getDocument() {
		return document;
	}

	public void setDocument(Document document) {
		this.document = document;
	}

	public AccordingManager getAccordingManager() {
		return accordingManager;
	}

	@Autowired
	public void setAccordingManager(AccordingManager accordingManager) {
		this.accordingManager = accordingManager;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	/**
	 * taskid
	 * 
	 * @return the taskid
	 * @since 1.0.0
	 */

	public String getTaskid() {
		return taskid;
	}

	/**
	 * @param taskid
	 *            the taskid to set
	 */
	public void setTaskid(String taskid) {
		this.taskid = taskid;
	}

	public Page<Document> getPage() {
		return page;
	}

	public void setPage(Page<Document> page) {
		this.page = page;
	}

	@Override
	public Document getModel() {
		// TODO Auto-generated method stub
		return document;
	}

	@Override
	public String list() throws Exception {
		// TODO Auto-generated method stub
		QueryFilter fileter = QueryFilter.buildFromHttpRequest(Struts2Utils
				.getRequest());
		if (page.isOrderBySetted()) {
			page.setOrder(Page.DESC);
			page.setOrderBy("createDate");
		}
		page.setPageSize(10);
		page = accordingManager.findPageDocument(page, fileter);
		return SUCCESS;
	}

	@Override
	public String input() throws Exception {
		// TODO Auto-generated method stub
		return INPUT;
	}

	@Override
	public String save() throws Exception {
		document.setPid(projectId);
		document.setStatus("01");
		accordingManager.saveDocument(document);
		id = document.getId();
		return "itemList";
	}

	public String qianding() throws Exception {
		return "qianding";
	}

	public void prepareQianding() throws Exception {
		prepareModel();
	}

	public void modk() throws Exception {
		document.setSign("1");
		if (null != upload) {
			Attachment attachmention = new Attachment();
			attachmention.setUpfile(upload);
			attachmention.setUpfileFileName(uploadFileName);
			attachmention.setUpfileContentType(uploadContentType);
			attachmention.setTableId(document.getId());
			attachmention.setTableField("document_attachment");
			attachmention.setTableName("document");
			systemManager.uploadFile(Struts2Utils.getAppRootPath(),
					attachmention);
			attachmention.setCreateDate(DateUtils.getCurrentDate());
			document.setAttachment(attachmention);
			accordingManager.saveDocument(document);
		} else {
			accordingManager.saveDocument(document);
		}
	}

	public void prepareModk() throws Exception {
		prepareModel();
	}

	@Override
	public String delete() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void prepareModel() throws Exception {
		// TODO Auto-generated method stub
		if (StringUtils.isNotEmpty(id)) {
			document = accordingManager.findDocumentByValue("id", id);
		} else {
			document = new Document();
		}
	}

	/**
	 * 业务流转 judge: 适用:
	 * 
	 * @return
	 * @throws Exception
	 * @exception
	 * @since 1.0.0
	 */
	public String judge() throws Exception {
		String result = null;
		taskid = accordingManager.isPersonalTasks(user, id,
				Constants.DOCUMENT_ID);
		status = document.getStatus();
		if (StringUtils.isEmpty(taskid)) {
			result = RELOAD;
		} else {
			result = Constants.START;
		}
		projectId = document.getPid();
		Struts2Utils.getSession().setAttribute("projectId", document.getPid());
		return result;
	}

	public void prepareJudge() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			document = accordingManager.findDocumentByValue("id", id);
		} else {
			document = new Document();
		}
	}

	/**
	 * 指定处理人员 login: 适用:
	 * 
	 * @return
	 * @throws Exception
	 * @exception
	 * @since 1.0.0
	 */
	public String login() throws Exception {
		return LOGIN;
	}

	public void prepareLogin() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			document = accordingManager.findDocumentByValue("id", id);
		} else {
			document = new Document();
		}
	}

	public String assign() throws Exception {
		return Constants.ASSIGN;
	}

	public void prepareAssign() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			document = accordingManager.findDocumentByValue("id", id);
		} else {
			document = new Document();
		}
	}

	/**
	 * 合同上报 start: 适用:
	 * 
	 * @return
	 * @throws Exception
	 * @exception
	 * @since 1.0.0
	 */
	public String start() throws Exception {
		String usernames = Struts2Utils.getParameter("usernames");
		String deploymentId = fProjectManager.getByKey("document")
				.getDeploymentId();
		String key = Struts2Utils.getParameter("key");
		String value = Struts2Utils.getParameter("value");
		String key1 = Struts2Utils.getParameter("key1");
		String value1 = Struts2Utils.getParameter("value1");
		Map<String, Object> variables = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(key)) {
			variables.put(key, value);
		}
		if (StringUtils.isNotEmpty(key1)) {
			variables.put(key1, value1);
		}
		if (StringUtils.isNotEmpty(usernames)) {
			variables.put("usernames", usernames);
		}
		variables.put(Constants.DOCUMENT_ID, id);
		accordingManager.start(id, deploymentId, "convey", variables);
		return Constants.OVER;
	}

	public void prepareStart() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			document = accordingManager.findDocumentByValue("id", id);
		} else {
			document = new Document();
		}
	}

	/**
	 * 接受任务 taketask: 适用:
	 * 
	 * @return
	 * @throws Exception
	 * @exception
	 * @since 1.0.0
	 */
	public String taketask() throws Exception {
		HistoryProject historyProject = historyProjectManager.get(taskid);
		String activityName = accordingManager.getTask(taskid)
				.getActivityName();
		if (historyProject == null) {
			historyProject = new HistoryProject();
			historyProject.setKey(id);
			historyProject.setUserName(user.getUserName());
			historyProject.setStatus("000" + status);
			historyProject.setStartDate(new Date());
			historyProject.setTaskId(taskid);
			historyProject.setActivityName(activityName);
		}
		try {
			accordingManager.takeTask(taskid, user);
			historyProjectManager.save(historyProject);
		} catch (org.jbpm.api.JbpmException e) {
			historyProjectManager.save(historyProject);
		}
		ControlHelpUtil.setObjectToSession("taskid", taskid);
		if (StringUtils.equals(activityName, "合同审定")) {
			return "part1";
		} else if (StringUtils.equals(activityName, "审核")) {
			return "part2";
		} else if (StringUtils.equals(activityName, "签发")) {
			return "part3";
		}
		return null;
	}

	public void prepareTaketask() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			document = accordingManager.findDocumentByValue("id", id);
		} else {
			document = new Document();
		}
	}
	
	public String one() throws Exception {
		return "one";
	}
	
	public void prepareOne() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			document = accordingManager.findDocumentByValue("id", id);
		} else {
			document = new Document();
		}
	}
	
	public String two() throws Exception {
		return "two";
	}
	
	public void prepareTwo() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			document = accordingManager.findDocumentByValue("id", id);
		} else {
			document = new Document();
		}
	}
	
	public String three() throws Exception {
		return "three";
	}
	
	public void prepareThree() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			document = accordingManager.findDocumentByValue("id", id);
		} else {
			document = new Document();
		}
	}
	
	/**
	 * 提交
	 * submit:
	 * 适用:
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public String submit() throws Exception {
		String outcome = Struts2Utils.getParameter("outcome");
		String view = Struts2Utils.getParameter("view");
		String key = Struts2Utils.getParameter("key");
		String value = Struts2Utils.getParameter("value");
		String key1 = Struts2Utils.getParameter("key1");
		String value1 = Struts2Utils.getParameter("value1");
		String count = Struts2Utils.getParameter("count");
		String leader = Struts2Utils.getParameter("leader");
		Map<String, Object> variables = new HashMap<String, Object>();
		HistoryProject historyProject = historyProjectManager.get(taskid);
		historyProject.setEndDate(new Date());
		historyProject.setMessage(user.getName() + "：" + view);
		if (StringUtils.isNotEmpty(key)) {
			variables.put(key, value);
		}
		if (StringUtils.isNotEmpty(key1)) {
			variables.put(key1, value1);
		}
		if (StringUtils.isNotEmpty(count)) {
			variables.put("count", count);
		}
		if (StringUtils.isNotEmpty(leader)) {
			variables.put("leader", leader);
		}
		accordingManager.completeTask(taskid, outcome, variables);
		accordingManager.saveDocument(document);
		historyProjectManager.save(historyProject);
		return Constants.OVER;
	}
	
	public void prepareSubmit() throws Exception {
		if (StringUtils.isNotEmpty(id)) {
			document = accordingManager.findDocumentByValue("id", id);
		} else {
			document = new Document();
		}
	}

}
